<template>
  <div class="checkTask">
    <!-- 导航栏 -->
    <div class="header_body">
      <header-nav :leftArrow="true" titelText="任务检查"></header-nav>
    </div>

    <div class="checkForm">
      <upload-pictrue :fileType="3" :titelText="'建筑物照片（可传3张）'" :fileList="fileList" :imgType="0"
        @fileListFun="fileListFun"></upload-pictrue>
      <div class="line10"></div>
      <div class="yinH">
        <div class="checkItem" v-for="(item, index) in ruleItemRespList" :key="index">
          <div class="checkItem-title" @click="openItem(index)">
            <div class="text">
              <div class="icon"></div>
              <div class="txt">{{ item.name }}</div>
            </div>
            <img class="img" src="../../assets/images/modelClose.png" alt="" v-if="ruleClose[index]" />
            <img class="img" src="../../assets/images/modelOpen.png" alt="" v-else />
          </div>
          <van-collapse v-model="activeNames" v-if="ruleClose[index] && item.childList != ''">
            <van-collapse-item v-for="(child, i) in item.childList" :key="i" :name="child.id">
              <template #title>
                <div class="ruleItemTitle">
                  <img src="../../assets/images/lsIcon.png" alt="" />
                  <div>
                    {{ child.name }}
                  </div>
                </div>
              </template>
              <div class="childList-1">
                <div class="childList-title">1、重要事项</div>
                <div class="childList-item" v-for="(detail, j) in child.detailList" :key="j">
                  <van-checkbox v-model="detail.checked" icon-size="20px">
                    {{ detail.checkItem }}
                  </van-checkbox>
                </div>
              </div>
              <div class="childList-2">
                <div class="childList-title">2、其他事项</div>
                <div class="childList-item">
                  <van-field v-model="child.others" rows="2" autosize type="textarea" maxlength="50"
                    placeholder="请输入" />
                </div>
              </div>
              <div class="childList-2">
                <div class="childList-title">3、抽查部位</div>
                <div class="childList-item">
                  <van-field v-model="child.spot" rows="2" autosize type="textarea" maxlength="50" placeholder="请输入" />
                </div>
              </div>
              <div class="childList-2">
                <div class="childList-title">4、具体情形</div>
                <div class="childList-item">
                  <van-field v-model="child.specific" rows="2" autosize type="textarea" maxlength="50"
                    placeholder="请输入" />
                </div>
              </div>
            </van-collapse-item>
          </van-collapse>
          <div v-if="ruleClose[index] && item.childList == ''" style="border-top: 1px solid #f5f5f5">
            <div class="childList-1">
              <div class="childList-title">1、重要事项</div>
              <div class="childList-item" v-for="(detail, i) in item.detailList" :key="i">
                <van-checkbox v-model="detail.checked">
                  {{ detail.checkItem }}
                </van-checkbox>
              </div>
            </div>
          </div>
          <div class="childList-2" v-if="ruleClose[index] && item.childList == ''">
            <div class="childList-title">2、其他事项</div>
            <div class="childList-item">
              <van-field v-model="item.others" rows="2" autosize type="textarea" maxlength="50" placeholder="请输入" />
            </div>
          </div>
          <div class="childList-2" v-if="ruleClose[index] && item.childList == ''">
            <div class="childList-title">3、具体情形</div>
            <div class="childList-item">
              <van-field v-model="item.specific" rows="2" autosize type="textarea" maxlength="50" placeholder="请输入" />
            </div>
          </div>
          <div class="line4" v-if="index != ruleClose.length - 1"></div>
        </div>
      </div>
      <div class="line10"></div>
      <div class="result1">
        <div class="title">
          <span style="color: #ee0a24; margin-right: 2px">*</span>结果判断
        </div>
        <van-radio-group v-model="checkForm.checkResult" direction="horizontal">
          <van-radio :name="1" style="margin-right: 52px">合格</van-radio>
          <van-radio :name="2">不合格</van-radio>
        </van-radio-group>
      </div>
      <van-field v-if="checkForm.checkResult == 2" style="padding: 16px !important; border-bottom: 1px solid #f5f5f5"
        v-model="checkForm.remark" rows="2" autosize type="textarea" required placeholder="请输入不合格原因" maxlength="32" />
      <van-field v-if="signFlag == ''" style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link
        required readonly label="主办人签字" :placeholder="signNames[0] == '' ? '去签字' : '查看签名'" @click="goSign(0)" />
      <div class="result1" :style="sign1 == '' ? 'justify-content: space-between' : ''" v-else>
        <div class="title">
          <span style="color: #ee0a24; margin-right: 2px">*</span>主办人签字
        </div>
        <div style="
            color: var(--van-primary-color);
            padding: 5px 12px;
            border: 1px solid rgba(23, 100, 206, 1);
            border-radius: 4px;
          " @click="oneSign()" v-if="sign1 == ''">
          一键签名
        </div>
        <div style="
            color: #a6a6a6;
            flex-grow: 1;
            display: flex;
            justify-content: space-between;
          " v-else @click="goSign(0)">
          <div>查看签名</div>
          <img style="width: 11px; height: 18px" src="../../assets/images/icon_chevron.png" alt="" />
        </div>
      </div>
      <van-field style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link required readonly
        label="协办人签字" :placeholder="signNames[1] == '' ? '去签字' : '查看签名'" @click="goSign(1)" />
      <van-field style="padding: 16px !important; border-bottom: 1px solid #f5f5f5" is-link required readonly
        label="被检查单位人员签字" :placeholder="signNames[2] == '' ? '去签字' : '查看签名'" @click="goSign(2)" />
      <div class="submitBtn">
        <van-button plain block type="primary" class="btn-left" native-type="submit" style="margin-right: 8px"
          @click="submitCheck(0)">
          保存当前并返回
        </van-button>
        <van-button block class="btn-right" type="primary" @click="submitCheck(1)">
          提交检查
        </van-button>
      </div>
    </div>
    <!-- 签名 -->
    <van-popup v-model:show="signPicker" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature background-color="#F7F7F7" v-if="sign1 == ''" @submit="signSubmit" @clear="onClear" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image :src="sign1" />
        <div style="width:100%;display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(1)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(1)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup v-model:show="signPicker2" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature background-color="#F7F7F7" v-if="sign2 == ''" @submit="signSubmit2" @clear="onClear2" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image :src="sign2" />
        <div style="width:100%;display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(2)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(2)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
    <van-popup v-model:show="signPicker3" round position="bottom" :close-on-click-overlay="false" closeable>
      <van-signature background-color="#F7F7F7" v-if="sign3 == ''" @submit="signSubmit3" @clear="onClear3" />
      <div v-else style="text-align: right; padding: 8px">
        <van-image :src="sign3" />
        <div style="width:100%;display: flex; justify-content: end">
          <van-button type="primary" size="small" plain @click="close(3)" style="margin-right: 5px">
            关闭
          </van-button>
          <van-button type="primary" size="small" @click="reSign(3)">
            重新签名
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script setup>
import { showNotify, showSuccessToast, showFailToast } from 'vant'
import { imgUrlToBase64 } from '../../util/util'
const { useTasks, usePublic } = $globalStore
const router = useRouter()
const route = useRoute()
const id = ref(route.query.id)
const from = ref(route.query.from)
const signFlag = ref(JSON.parse(sessionStorage.getItem('userInfo')).userSign)

//检查图片信息
const fileList = ref([])
const fileListFun = (val) => {
  console.log(val, '图片')
  checkForm.placePhotoUrl = val.join(',')
}

const checkForm = reactive({
  taskCheckFillList: [], //隐患信息
  placePhotoUrl: '', // 检查照片
  checkResult: 1, //判断结果 1合格 2不合格
  remark: '',
  checkerSign: '', //检查人签字
  enterpriserSign: '', //被检查单位人员签名
  type: '',
  id: '',
})

const activeNames = ref(['1'])
const ruleItemRespList = ref([]) //检查列表数据
const ruleClose = ref([])
//关闭或打开检查项
const openItem = (i) => {
  ruleClose.value[i] = !ruleClose.value[i]
}

//去签字
const signPicker = ref(false)
const signPicker2 = ref(false)
const signPicker3 = ref(false)
const signNames = ref(['', '', ''])
const sign1 = ref('')
const sign2 = ref('')
const sign3 = ref('')
const goSign = (val) => {
  if (val == 0) {
    signPicker.value = true
  } else if (val == 1) {
    signPicker2.value = true
  } else {
    signPicker3.value = true
  }
}

const oneSign = async () => {
  const d = await usePublic.bindFileUrl(
    JSON.parse(sessionStorage.getItem('userInfo')).userSign
  )
  if (d.code == 0) {
    signNames.value[0] = d.data
    imgUrlToBase64(d.data).then((r) => {
      sign1.value = r
    })
  }
}

const signSubmit = async (val) => {
  sign1.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[0] = res.data.fileIds[0]
    }
  } else {
    signNames.value[0] = ''
  }
  signPicker.value = false
}
const signSubmit2 = async (val) => {
  sign2.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[1] = res.data.fileIds[0]
    }
  } else {
    signNames.value[1] = ''
  }
  signPicker2.value = false
}
const signSubmit3 = async (val) => {
  sign3.value = val.image
  if (val.image != '') {
    const res = await usePublic.uploadFile2({ contents: val.image })
    if (res.code == 0) {
      signNames.value[2] = res.data.fileIds[0]
    }
  } else {
    signNames.value[2] = ''
  }
  signPicker3.value = false
}

const reSign = (val) => {
  if (val == 1) {
    sign1.value = ''
  } else if (val == 2) {
    sign2.value = ''
  } else {
    sign3.value = ''
  }
}

const close = (val) => {
  if (val == 1) {
    signPicker.value = false
  } else if (val == 2) {
    signPicker2.value = false
  } else {
    signPicker3.value = false
  }
}

//提交检查
const submitCheck = async (val) => {
  checkForm.taskCheckFillList = []
  if (val == '1') {
    if (checkForm.placePhotoUrl == '') {
      return showNotify({ type: 'danger', message: '请上传建筑物照片' })
    } else if (checkForm.checkResult == 2 && checkForm.remark == '') {
      return showNotify({ type: 'danger', message: '请输入不合格原因' })
    } else if (signNames.value[0] == '' || signNames.value[1] == '') {
      return showNotify({ type: 'danger', message: '请检查人签名' })
    } else if (signNames.value[2] == '') {
      return showNotify({ type: 'danger', message: '请被检查单位人员签名' })
    }
  }
  checkForm.type = val
  checkForm.id = id.value
  checkForm.checkerSign = signNames.value[0] + ',' + signNames.value[1]
  checkForm.enterpriserSign = signNames.value[2]
  ruleItemRespList.value.forEach((item) => {
    if (item.childList == '') {
      let arr = []
      item.detailList.forEach((d, i) => {
        if (d.checked) {
          arr.push(i)
        }
      })
      let obj = {
        itemId: item.id,
        chooseItem: arr.join(','),
        others: item.others,
        specific: item.specific,
        spot: item.spot,
      }
      checkForm.taskCheckFillList.push(obj)
    } else {
      item.childList.forEach((c) => {
        let brr = []
        for (let index = 0; index < c.detailList.length; index++) {
          const element = c.detailList[index]
          if (element.checked) {
            brr.push(index)
          }
        }
        let obj = {
          itemId: c.id,
          chooseItem: brr.join(','),
          others: c.others,
          specific: c.specific,
          spot: c.spot,
        }
        checkForm.taskCheckFillList.push(obj)
      })
    }
  })
  console.log(checkForm)
  const res = await useTasks.uploadTask(checkForm)
  if (res.code == 0) {
    if (val == '0') {
      showSuccessToast('保存成功')
      if (from.value == 1) {
        router.push({
          name: 'tasksList',
        })
      } else {
        router.go(-1)
      }
    } else {
      showSuccessToast('检查成功')
      if (from.value == 1) {
        router.push({
          name: 'tasksList',
        })
      } else {
        router.go(-1)
      }
    }
  } else {
    showFailToast(res.message)
  }
}

onMounted(async () => {
  if (id.value) {
    fileList.value = []
    const res = await useTasks.taskInfo(id.value)
    if (res.code == 0) {
      checkForm.remark = res.data.remark
      checkForm.placePhotoUrl = res.data.placePhotoUrl
      if (res.data.placePhotoUrl != '') {
        let arr = res.data.placePhotoUrl.split(',')
        arr.forEach(async (element) => {
          const r = await usePublic.bindFileUrl(element)
          if (r.code == 0) {
            fileList.value.push(r.data)
          }
        })
      }
      if (res.data.taskCheckFillList == '') {
        checkForm.taskCheckFillList = []
      } else {
        checkForm.taskCheckFillList = res.data.taskCheckFillList
      }
      checkForm.checkResult = res.data.checkResult
      if (res.data.checkerSign != '') {
        let s = res.data.checkerSign.split(',')
        const r = await usePublic.bindFileUrl(s[0])
        if (r.code == 0) {
          signNames.value[0] = r.data
          imgUrlToBase64(r.data).then((s) => {
            sign1.value = s
          })
        }
        if (s[1]) {
          const d = await usePublic.bindFileUrl(s[1])
          if (d.code == 0) {
            signNames.value[1] = d.data
            imgUrlToBase64(d.data).then((r) => {
              sign2.value = r
            })
          }
        }
      }
      if (res.data.enterpriserSign != '') {
        const t = await usePublic.bindFileUrl(res.data.enterpriserSign)
        if (t.code == 0) {
          signNames.value[2] = t.data
          imgUrlToBase64(t.data).then((r) => {
            sign3.value = r
          })
        }
      }
      ruleItemRespList.value = res.data.ruleItemRespList
      ruleItemRespList.value.forEach((r) => {
        if (r.childList == '') {
          r.detailList.forEach((d) => {
            if (d.ruleId == 0) {
              Reflect.set(d, 'checked', false)
            } else {
              Reflect.set(d, 'checked', true)
            }
          })
        } else {
          r.childList.forEach((c) => {
            for (let d = 0; d < c.detailList.length; d++) {
              const element = c.detailList[d]
              if (element.ruleId == 0) {
                Reflect.set(element, 'checked', false)
              } else {
                Reflect.set(element, 'checked', true)
              }
            }
          })
        }
      })
      ruleClose.value = []
      ruleItemRespList.value.forEach((i, j) => {
        if (j == 0) {
          ruleClose.value.push(true)
        } else {
          ruleClose.value.push(false)
        }
      })
      console.log(ruleClose.value)
    }
  }
})
</script>
<style lang="scss" scoped>
.checkTask {
  width: 100%;
  height: calc(100%);
  overflow-y: hidden;
  background-color: #ffffff;

  .checkForm {
    width: 100%;
    height: calc(100% - 122px);
    overflow-y: auto;
    margin-top: 46px;

    .yinH {
      .checkItem {
        .checkItem-title {
          padding: 16px 12px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .text {
            display: flex;
            align-items: center;

            .icon {
              width: 4px;
              height: 14px;
              border-radius: 20px;
              background: linear-gradient(180deg,
                  rgba(86, 136, 245, 1) 0%,
                  rgba(23, 100, 206, 1) 100%);
              margin-right: 8px;
            }

            .txt {
              height: 24px;
              font-size: 17px;
              font-weight: 500;
              letter-spacing: 0px;
              line-height: 24px;
              color: #2b2b2b;
            }
          }

          .img {
            width: 20px;
            height: 20px;
          }
        }
      }
    }

    .result1 {
      padding: 16px;
      display: flex;
      border-bottom: 1px solid #f5f5f5;

      .title {
        width: 125px;
        font-size: 16px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 24px;
        color: #4d4d4d;
      }
    }
  }
}

.line4 {
  width: 100%;
  height: 4px;
  background-color: #f7f7f7;
}

.line10 {
  width: 100%;
  height: 10px;
  background-color: #f7f7f7;
}

.line16 {
  width: 100%;
  height: 16px;
  background-color: #f7f7f7;
}

.ruleItemTitle {
  display: flex;
  align-items: center;

  img {
    width: 18px;
    height: 18px;
    margin-right: 4px;
  }

  div {
    color: #4d4d4d;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 24px;
  }
}

.childList-1 {
  padding: 16px 16px 0 16px;

  .childList-title {
    padding-bottom: 16px;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 24px;
    color: #666666;
    border-bottom: 1px solid #f5f5f5;
  }

  .childList-item {
    padding: 16px 0;
    border-bottom: 1px solid #f5f5f5;
  }

  .childList-item:last-child {
    border-bottom: none;
  }
}

.childList-2 {
  .childList-title {
    padding: 16px 16px 0 16px;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 24px;
    color: #666666;
    border-top: 1px solid #f5f5f5;
  }
}

.checkTask .van-field__control {
  padding: 0 !important;
}
</style>
